package com.daxia.ogmall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.ogmall.dao.DecorateNoteDAO;
import com.daxia.ogmall.dto.DecorateNoteDTO;
import com.daxia.ogmall.model.DecorateNote;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.BeanMapper;

@Service
public class DecorateNoteService {
	
	@Autowired
	private DecorateNoteDAO decorateNoteDAO;
	
	public List<DecorateNoteDTO> find(DecorateNoteDTO query, Page page) {
		List<DecorateNote> models = decorateNoteDAO.find(query, page);
		List<DecorateNoteDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<DecorateNoteDTO> findAll() {
		return this.find(new DecorateNoteDTO(), null);
	}
	
	public List<DecorateNoteDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new DecorateNoteDTO(), page);
	}
	
	public Long create(DecorateNoteDTO dto) {
		DecorateNote model = new DecorateNote();
		toModel(model, dto);
		return decorateNoteDAO.create(model);
	}
	
	public DecorateNoteDTO load(Long id) {
	    DecorateNote model = decorateNoteDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(DecorateNoteDTO dto) {
		DecorateNote model = decorateNoteDAO.load(dto.getId());
		toModel(model, dto);
		decorateNoteDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				decorateNoteDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public DecorateNoteDTO findOne(DecorateNoteDTO query) {
		DecorateNote model = decorateNoteDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<DecorateNoteDTO> toDTOs(List<DecorateNote> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<DecorateNoteDTO>(0);
		}
		List<DecorateNoteDTO> dtos = new ArrayList<DecorateNoteDTO>(models.size());
		for (DecorateNote model : models) {
	        DecorateNoteDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private DecorateNoteDTO toDTO(DecorateNote model) {
		if (model == null) {
			return null;
		}
		DecorateNoteDTO dto = BeanMapper.map(model, DecorateNoteDTO.class);
		
		return dto;
	}
	
	private void toModel(DecorateNote model, DecorateNoteDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<DecorateNote> toModels(List<DecorateNoteDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<DecorateNote>(0);
		}
		List<DecorateNote> models = new ArrayList<DecorateNote>(dtos.size());
		for (DecorateNoteDTO dto : dtos) {
	        DecorateNote model = new DecorateNote();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
